iT邦幫忙

2022 iThome 鐵人賽

DAY 21
0
自我挑戰組

30天HackerRank 1 Month Preparation Kit系列 第 21

Day 21 Prime Dates用c++

  • 分享至 

  • xImage
  •  

題目

https://ithelp.ithome.com.tw/upload/images/20220921/20151833zkDR3vDmxT.png
https://ithelp.ithome.com.tw/upload/images/20220921/20151833W1NtREgcZu.png

解題想法

int month[15];

void updateLeapYear(int year) {
    if(year % 400 == 0) {
        month[2] = 29;
    } else if(year % 100 == 0) {
        month[2] = 28;
    } else if(year % 4 == 0) {
        month[2] = 29;
    } else {
        month[2] = 28;
    }
}

void storeMonth() {
    month[1] = 31;
    month[2] = 28;
    month[3] = 31;
    month[4] = 30;
    month[5] = 31;
    month[6] = 30;
    month[7] = 31;
    month[8] = 31;
    month[9] = 30;
    month[10] = 31;
    month[11] = 30;
    month[12] = 31;
}

int findLuckyDates(int d1, int m1, int y1, int d2, int m2, int y2) {
    storeMonth();

    int result = 0;

    while(true) {
        int x = d1;
        x = x * 100 + m1;
        x = x * 10000 + y1;
        if(x % 4 == 0 || x % 7 == 0) {
            result = result + 1;
        }
        if(d1 == d2 && m1 == m2 && y1 == y2) {
            break;
        }
        updateLeapYear(y1);
        d1 = d1 + 1;
        if(d1 > month[m1]) {
            m1 = m1 + 1;
            d1 = 1;
            if(m1 > 12) {
                y1 =  y1 + 1;
                m1 =  1;
            }
        }
    }
    return result;
}

結果

https://ithelp.ithome.com.tw/upload/images/20220921/20151833kVIukjm1l4.png
https://ithelp.ithome.com.tw/upload/images/20220921/201518334GSod19VTt.png


上一篇
Day 20 Grid Challenge用Javascript
下一篇
Day 22 Sherlock and Array用Golang
系列文
30天HackerRank 1 Month Preparation Kit30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言